
// Get all list ids and status
function GetListStatus(statusOption) {
    $("input:checkbox").each(function () {
        if (/^StatusChk_/i.test($(this).attr("id"))) {
            statusOption.Id.push($(this).val());
            if ($(this).is(":checked")) {
                statusOption.Status.push("Enabled");
            }
            else {
                statusOption.Status.push("Disabled");
			}
		}
	});
}

// Get all list ids and status
function GetListStatusOrg(statusOption) {
	var EmailOptionList = data.EmailTemplateList;
	if (data.EmailTemplateList.length > 0) {

		for (var i = 0; i < data.EmailTemplateList.length; i++) {
			statusOption.Id.push(data.EmailTemplateList[i].TemplateId);
			statusOption.Status.push(data.EmailTemplateList[i].Status);
		}
	}
}

var firstLoadForm = true;

var statusOptionsOrg = [];
statusOptionsOrg.Id = [];
statusOptionsOrg.Status = [];

var statusOptionsTemp = [];
statusOptionsTemp.Id = [];
statusOptionsTemp.Status = [];

var StatusOptionsUpdate = [];
StatusOptionsUpdate.Id = [];
StatusOptionsUpdate.Status = [];

//************ PRIVATE METHOD *************//
function GetCompanyNameById(_companyId) {
	var list = getLeadModel.CompanyOptions();
	for (var i = 0; i < list.length; i++) {
		if (list[i].Id == _companyId) {
			return list[i].Name;
		}
	}
}

// Delete by lead source id
function DeleteLeadSellerBy(_leadSourceId) {
	var dataPost = { "leadSellerId": _leadSourceId };
	var urlPost = "/SetUpWizard/RemoveLeadSeller";

	closePopup();
	openProcess();

	$.ajax({ type: "POST", url: urlPost, data: dataPost, dataType: "json",
		success: function (returnData, textStatus, jqXHR) {
		    if (returnData.Error == undefined || returnData.Error == null) {
		        hideProcess();
				if (returnData == "") {
					if (getLeadModel.leadSellerList().length > 0) {
						for (var i = 0; i < getLeadModel.leadSellerList().length; i++) {
							if (getLeadModel.leadSellerList()[i].Id == _leadSourceId) {
								//Remove item here
								getLeadModel.leadSellerList.splice(i, 1);
								break;
							}
						}
					}
				}
				else {
					if (returnData.ErrorCode.toString() == '1288') {
						
						showAlertPopup(_leadSourceId, returnData.ErrorCode.toString());
					}
					else {
						var message = returnData;
						showAlertPopup(message, '');
					}
				}
			}
			else {
				hideProcess();
				showPopupError();
			}
		},
		error: function (xhr, status, error) {

			hideProcess();
			showPopupError();
		}
	}); // End ajax post
}

function ConnectWebform(listEmail) {
	var dataPost = { "email": listEmail.toString() };
	var urlPost = "/SetUpWizard/ConnectWebform";

	// Json Get function to retrive data from server
	openEmailProcess();

	$.ajax({ type: "POST", url: urlPost, data: dataPost, dataType: "json",
	    success: function (returnData, textStatus, jqXHR) {
	        hideEmailProcess();
	        if (returnData.Error == undefined || returnData.Error == null) {
	            if (returnData == "") {
	                getLeadModel.showSuccess(true);
	                getLeadModel.showEmailMessage(false);
	                $('#iptEmailInput').val("");
	                $('#iptEmailInput').removeClass("focus");
	                $('#iptEmailInput').removeClass("text-active");
	            }
	            else {
	                showAlertPopup(returndata.toString(), '');
	            }
	        }
	        else {
	            showPopupError();
	        }
	    },
	    error: function (xhr, status, error) {

	        hideEmailProcess();
	        showPopupError();
	    }
	});  // End ajax post
}

function FormatPrice(priceInput) {
	return priceInput ? parseFloat(priceInput).toFixed(2) : "0";
}

function expectKeyUp(evt) {
	getLeadModel.showExpectErrMessage(false);
}

function companyKeyUp(evt) {
	if ($("#ddlCompanyList").find('.center').text() != "Select Company")
		getLeadModel.showCompanyErrMessage(false);
}

function existContractKeyUp(evt) {
	getLeadModel.showExistContractErrMessage(false);
}

function emailListKeyUp(evt) {
	getLeadModel.showSuccess(false);
	getLeadModel.showEmailMessage(false);
}


function validateListEmail(emailSendList) {
	//var emailRegular = new RegExp("^([\\w-]+(?:\\.[\\w-]+)*)@((?:[\\w-]+\\.)*\\w[\\w-]{0,66})\\.([a-z]{2,6}(?:\\.[a-z]{2})?)$");
	var emailRegular = new RegExp(PARAM_EMAIL);

	for (var i = 0; i < emailSendList.length; i++) {
		if (!emailRegular.test($.trim(emailSendList[i]))) {
			return false;
		}
	}

	return true;
}

function validateAreaCode(areaCode) {
	var areaCodeRegular = new RegExp(PARAM_AREA_CODE);

	if (areaCodeRegular.test(areaCode))
		return true;

	return false;
}

function validateInboundPhone(phone) {
	var phoneInboundRegular = new RegExp(PARAM_INBOUND_PHONE);
	if (phoneInboundRegular.test(phone))
		return true;

	return false;
}

function formatListEmail(emailSendList) {
	var output = "";
	if (emailSendList.length == 1) {
		output = $.trim(emailSendList[0]);
	}
	else {
		for (var i = 0; i < emailSendList.length; i++) {
			output += $.trim(emailSendList[i]);
			if (i != emailSendList.length - 1) output += ",";
		}
	}

	return output;
}

function SetupOptionEmails() {
	if (firstLoadForm) {
		statusOptionsOrg = [];
		statusOptionsOrg.Id = [];
		statusOptionsOrg.Status = [];
		GetListStatusOrg(statusOptionsOrg);
	}
	firstLoadForm = false;
}

// Show new user alert fancybox
function showAlertPopup(itemName, errorCode) {
	if (errorCode == '1288')
		$('#itemName').text('<' + itemName + '> cannot be deleted because it is associated with at least one lead.');
	else
		$('#itemName').text(itemName);

	$('#alertPopup').showPopup({
		width: 480
	});
    $('#fancybox-overlay').show();
}

// Window load
//window.addLoadEvent(function() { setInterval("doDeleteLeadSellerLinks()", 100); });


$('#iptExpectedCost').blur(function () {
	setTimeout(function () {
		$('#iptExpectedCost').removeClass("focus");
		$('#iptExpectedCost').removeClass("text-active");
	}, 1);
});

function closePreviewEmail() {
	$('#previewEmail').hide();
	$('#fancybox-overlay').hide();
	$(".fancybox-wrap").hide();
}
function closeAlertPopup() {
	$('#confirmDeleteUser').hide();
	$('#fancybox-overlay').hide();
	$(".fancybox-wrap").hide();
}
function closeTeamOneUser() {
	$('#lightTeamOneUser').hide();
	$('#fancybox-overlay').hide();
	$(".fancybox-wrap").hide();
}
function closeTooManyUserPopup() {
	$('#tooManyUserPopup').hide();
	$('#fancybox-overlay').hide();
	$(".fancybox-wrap").hide();
}

function openProcess() {
    $.fancybox($('#popup-process'), {
        padding: 0,
        closeBtn: false,
        helpers: {
            overlay: {
                opacity: 0.6,
                css: {
                    'background-color': '#11619D'
                }
            }
        },
        beforeClose: function () {
            return false;
        }
    });
    $('.fancybox-skin').show();
    $('#fancybox-overlay').show();
}
function hideProcess() {
    $('#popup-process').hide();
    $('.fancybox-skin').hide();
    $('#fancybox-overlay').hide();
}

/*----------------------------------------------------------------
FUNCTIONS---------------------------------------------/*
/*to post the seleted file*/
function ContinueClick() {
	init_mapping();
	document.getElementById("UploadFile").click();
}

function init_review_import() {
	$.fancybox($('#popup-processing-reviewimport'), {
		padding: 0,
		closeBtn: false,
		helpers: {
			overlay: {
				opacity: 0.6,
				css: {
				    'background-color': '#11619D'
				},
				closeClick: true
			}
		}

	}); 
}

function ChangeViewType(vt) {
	getLeadModel.ViewType = vt;
	if (getLeadModel.Initialized) {
	    getLeadModel.UpdateView();
	}
}

//Edit cell
function Keypress_Event(evt, value, id) {
	var charCode = (evt.which) ? evt.which : evt.keyCode
	if (charCode == 13 || charCode == 9) {
		Update_Cell(value, id);
	}
	return true;
}
//Validation cell
function Update_Cell(value, id) {
	var _arrayId = id.split('-');
	var _row = _arrayId[1];
	var _cell = _arrayId[0];
	var _ArrayErrorRows = getLeadModel.ErrorRows();
	var _ArrayValidation = getLeadModel.ColumnHeaders()[_cell].RegularExpressions;
	var _IsRequired = getLeadModel.ColumnHeaders()[_cell].IsRequired;
	var _check = false;
	if (_IsRequired) {
		if (value != "") {
			if (_ArrayValidation.length > 0) {
				for (var i = 0; i < _ArrayValidation.length; i++) {
					if (CheckValidation(value, _ArrayValidation[i])) {
						_check = true;
						break;
					}
				}
			}
			else {
				_check = true;
			}
		}
		else {
			_check = false;
		}
	}
	else {
		if (value != "") {
			if (_ArrayValidation.length > 0) {
				for (var i = 0; i < _ArrayValidation.length; i++) {
					if (CheckValidation(value, _ArrayValidation[i])) {
						_check = true;
						break;
					}
				}
			}
			else {
				_check = true;
			}
		}
		else {
			_check = true;
		}
	}


	if (_check) {
		_ArrayErrorRows[_row].Cells[_cell].Value = value;
		_ArrayErrorRows[_row].Cells[_cell].IsDone = true;
		_ArrayErrorRows[_row].Cells[_cell].IsError = false;
		_ArrayErrorRows[_row].Cells[_cell].ClassName = "col1 done";
		//getLeadModel.ErrorRows([]);
		getLeadModel.ErrorRows(_ArrayErrorRows);
	}
	else {
		_ArrayErrorRows[_row].Cells[_cell].Value = value;
		_ArrayErrorRows[_row].Cells[_cell].IsDone = false;
		_ArrayErrorRows[_row].Cells[_cell].IsError = true;
		_ArrayErrorRows[_row].Cells[_cell].ClassName = "col1 error";
		//getLeadModel.ErrorRows([]);
		getLeadModel.ErrorRows(_ArrayErrorRows);
	}

	//Check show scroll toltip
    $('#scrollbar').css("display", "none");
}

//Check validation
function CheckValidation(value, pattern) {
	var regExp = new RegExp(pattern, "");
	return regExp.test(value);
}
//to check to show tooltip
function showtoltip() 
{
    $('#gridview').scroll(function () {
        var scrollleft = $("#gridview").scrollLeft();


        if (scrollleft > 0)
         {
            $('#scrollbar').css("display", "none");

        }
        else if (ReviewImportModel.CountError() > 0) {
            $('#scrollbar').css("display", "block");
        }
    });
}

// Normalize cols height
function fix_table_cols_height_tableSetup(table) {
    table.each(function (id, table) {
        table = $(table);

        //Add table-ignore to exclude it from this function
        if (table.hasClass('table-fixed')) return;

        var title_h = table.find('>.title').height();


        if (title_h == 0) {
            var col_h = table.find('.title .col1').outerHeight(true);
            //table.find('.title').height(col_h);
            var title_h = table.find('.title').height();
        }

        table.find('>.title .col1').each(function (idx, el) {
            if ($(el).find('.w').length > 0) {
                var extra = $(el).find('.w').outerHeight(true) - $(el).find('.w').height();
                $(el).find('.w').css('min-height', (title_h - extra));
            } else {
                var extra = $(el).outerHeight(true) - $(el).height();
                $(el).css('min-height', (title_h - extra));
            }
            //$(el).find('.w').css('height',title_h-20);
        });

        $('div.line', table).each(function (idx_line, el_line) {
            var line_h = $(el_line).height();
            if (line_h == 0) {
                var col_h = table.find('.title .col1').outerHeight(true);
                $(el_line).height(col_h);
                var line_h = $(el_line).height();
            }

            $(el_line).find('>.col1').each(function (idx_col, el_col) {
                if ($(el_col).find('.w').length > 0) {
                    var extra = $(el_col).find('.w').outerHeight(true) - $(el_col).find('.w').height();
                    $(el_col).find('.w').css('min-height', (line_h - extra));
                } else {
                    var extra = $(el_col).outerHeight(true) - $(el_col).height();
                    $(el_col).css('min-height', (line_h - extra));
                }
            });
        });

    }); // end each
}



// Normalize cols height of setup wizard - Add your team
function fix_table_cols_height_tableStep1(table) {
    table.each(function (id, table) {
        table = $(table);

        //Add table-ignore to exclude it from this function
        if (table.hasClass('table-fixed')) return;

        $('tr', table).each(function (idx_line, el_line) {
            var line_h = $(el_line).height();

            $('td', el_line).each(function (idx_td, el_td) {
                if (idx_td == 0) {
                    var num_extra = Math.ceil((line_h - 37) / 2);
                    var num_padding = (9 + num_extra).toString() + "px 8px";
                    el_td = $(el_td);
                    var number_h = el_td.find('.number');
                    number_h.css("padding", num_padding);
                }
            });
        });
    }); // end each
}

function closePopup() {
    $('#tooManyUserPopup').hide();
    $('#lightTeamOneUser').hide();
    $('#fancybox-overlay').hide();
    $(".fancybox-wrap").hide();
}

function AddBorderRightClass() {
    if ($('#listUsers').length) $('#listUsers').find('.col5').removeClass("noborder-right");
    if ($('.tablefix-title').length) $('.tablefix-title').find('.col5').removeClass("noborder-right");
}

function RemoveBorderRightClass() {
    if ($('#listUsers').length) $('#listUsers').find('.col5').addClass("noborder-right");
    if ($('.tablefix-title').length) $('.tablefix-title').find('.col5').addClass("noborder-right");
}
function FixBorderTableClass() {
    if ($('#listUsers').length) {
        $('#listUsers tr:last-child td').addClass("noborder-bottom");
        $('#listUsers tr:first-child td').addClass("border-top");
    }

    //$("table tr td:first-child").text('hello');
}

function clone(src) {
    function mixin(dest, source, copyFunc) {
        var name, s, i, empty = {};
        for (name in source) {
            // the (!(name in empty) || empty[name] !== s) condition avoids copying properties in "source"
            // inherited from Object.prototype.   For example, if dest has a custom toString() method,
            // don't overwrite it with the toString() method that source inherited from Object.prototype
            s = source[name];
            if (!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))) {
                dest[name] = copyFunc ? copyFunc(s) : s;
            }
        }
        return dest;
    }

    if (!src || typeof src != "object" || Object.prototype.toString.call(src) === "[object Function]") {
        // null, undefined, any non-object, or function
        return src;  // anything
    }
    if (src.nodeType && "cloneNode" in src) {
        // DOM Node
        return src.cloneNode(true); // Node
    }
    if (src instanceof Date) {
        // Date
        return new Date(src.getTime());  // Date
    }
    if (src instanceof RegExp) {
        // RegExp
        return new RegExp(src);   // RegExp
    }
    var r, i, l;
    if (src instanceof Array) {
        // array
        r = [];
        for (i = 0, l = src.length; i < l; ++i) {
            if (i in src) {
                r.push(clone(src[i]));
            }
        }
        // we don't clone functions for performance reasons
        //    }else if(d.isFunction(src)){
        //      // function
        //      r = function(){ return src.apply(this, arguments); };
    } else {
        // generic objects
        r = src.constructor ? new src.constructor() : {};
    }
    return mixin(r, src, clone);

}

// Progress Bar
function openEmailProcess() {
    $('.fancybox-skin').show();
    $('#fancybox-overlay').show();
    $.fancybox($('#email-sending-popup'), {
        padding: 0,
        closeBtn: false,
        helpers: {
            overlay: {
                opacity: 0.6,
                css: {
                    'background-color': '#11619D'
                }
            }
        },
        beforeClose: function () {
            return false;
        }
    });
}
function hideEmailProcess() {
    $('.fancybox-skin').hide();
    $('#fancybox-overlay').hide();
    $.fancybox.close();
}
function closeAddPhoneAlert() {
    $('#addPhoneAlert').hide();
    $('.fancybox-skin').hide();
    $('#fancybox-overlay').hide();
}